package com.g2room.java8;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;

/**
 * 日期时间类示例
 */
public class DateTimeSample {

    public static void clockSample() {
        System.out.println("********************* Clock *********************");
        Clock clock = Clock.systemDefaultZone();
        // Clock是对当前时区敏感的，并可用于替代System.currentTimeMillis()方法来获取当前的毫秒时间
        System.out.println(clock.millis());
        Clock clock1 = Clock.systemUTC();
        System.out.println(clock1.millis());
        Instant instant = clock.instant();
        Date date = Date.from(instant);
        System.out.println(date);
    }

    /**
     * ZoneId来表示时区类。时区类的对象可以通过静态工厂方法方便地获取。
     * 时区类还定义了一个偏移量，用来在当前时刻或某时间与目标时区时间之间进行转换。
     * LocalTime表示一个没有指定时区的时间，它是由多个工厂方法组成，其目的是为了简化对时间对象实例的创建和操作，包括对时间字符串进行解析的操作。
     * LocalDate本地时间表示了一个独一无二的日期，可以通过加减日，月，年等指标来计算新的日期。记住，每一次操作都会返回一个新的时间对象。
     * LocalDateTime表示的是日期-时间。
     */
    public static void datetimeSample() {
        System.out.println("********************* Zone and LocalTime *********************");
        // 查看所有时区
        System.out.println(ZoneId.getAvailableZoneIds());
        // 东八区
        ZoneId zone2 = ZoneId.of("Etc/GMT-8");
        // 获取时区规则
        System.out.println(zone2.getRules());
        ZoneId zone1 = ZoneId.of("Etc/GMT0");
        LocalTime now1 = LocalTime.now(zone1);
        LocalTime now2 = LocalTime.now(zone2);
        // false
        System.out.println("now1 = " + now1 + ", now2 = " + now2 + ", now1 before now2= " + now1.isBefore(now2));

        // 内置工具类获取各个数值差
        long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
        long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
        System.out.println("hours = " + hoursBetween + ", minutes = " + minutesBetween);

        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
        LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
        // 格式化，按不同国家表示时间格式
        DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.CANADA);
        DateTimeFormatter germanFormatterZh = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.CHINESE);
        String tomorrowDate = germanFormatter.format(tomorrow);
        System.out.println("today is " + today + ", tomorrow is " + tomorrow + ", next Month is " + nextMonth
                + ", CANADA format is " + tomorrowDate+ ", CHINESE format is " + germanFormatterZh.format(tomorrow));

        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter germanFormatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.CHINESE);
        System.out.println("CHINESE format is " + germanFormatter1.format(localDateTime));
    }
}
